<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\kuaishou;

use app\model\BatchCreateSchemaUriModel;
use app\service\client\KuaiShouAccountService;
use app\service\fetch\MediaService;
use app\service\material\KuaiShouSchemaService;
use think\facade\Db;

abstract class KuaiShouService extends MediaService
{
    /**
     * @var array 物料列表
     */
    protected static array $schemaUrlModelList = [];

    /**
     * @var array 物料对应账户列表
     */
    protected static array $schemaUrlAdvList = [];

    /**
     *  更新账户中对应物料视频数.
     *
     * @param string $userId 客户id
     * @param string $videoName 视频名称
     */
    protected static function updateSchemaUrlVideoNum(string $userId = '', string $videoName = ''): bool
    {
        if (! $userId || ! $videoName) {
            return self::setError('更新直达链接素材数时参数错误');
        }
        try {
            // 获取userId下所有账户id
            if (! isset(self::$schemaUrlAdvList[$userId])) {
                self::$schemaUrlAdvList[$userId] = (new KuaiShouAccountService())->getAdvertiserByUserId($userId);
            }

            $advertiserIds = self::$schemaUrlAdvList[$userId];
            if (! $advertiserIds) {
                return true;
            }

            if (! isset(self::$schemaUrlModelList[$userId])) {
                self::$schemaUrlModelList[$userId] = Db::name('batch_create_schema_uri')->whereIn('advertiser_id', $advertiserIds)->force('advertiser_id_2')->find();
            }
            $model = self::$schemaUrlModelList[$userId];

            if (! $model instanceof BatchCreateSchemaUriModel || ! $model->getKey()) {
                return true;
            }

            // 截取直达链接媒体id
            $videoName = explode('-', $videoName);
            if (! $videoName) {
                return self::setError('更新直达链接素材数时视频名称不符合');
            }
            $materialId = $videoName[0];
            // 获取直达链接媒体视频数量
            $num = KuaiShouSchemaService::getEnableMaterialVideoNum($userId, $materialId);
            // 更新表视频数量表
            (new BatchCreateSchemaUriModel())->whereIn('advertiser_id', $advertiserIds)
                ->where('material_id', $materialId)
                ->update([
                    'has_material' => $num,
                    'update_time' => time(),
                ]);

            return true;
        } catch (\Exception $e) {
            return self::setError('更新直达链接素材数错误:' . $e->getMessage());
        }
    }
}
